package com.kylin.common.weixin.util;

import com.alibaba.fastjson2.JSONObject;
import com.kylin.common.core.util.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 微信请求工具
 *
 * @author wuhao
 * @version 1.0 - 2019-03-04
 */
public class WxRequest {

    public static Logger logger = LoggerFactory.getLogger(WxRequest.class);


    /**
     * get请求
     * @param url 请求地址
     * @return json格式数据
     * @version 1.0  by wuhao at 2019-03-04
     */
    public static JSONObject get(String url){
        long begin = System.currentTimeMillis();
        String result = "";
        if(!url.startsWith("http")) {
            url = WechatConstants.WX_API_URL + url;
        }
        try {
            result = HttpClientUtils.get(url);
            return JSONObject.parseObject(result);
        }catch (Exception e){
            logger.error(url,e);
            throw  e;
        }finally {
            logger.info("\n【微信请求地址】: {}\n【微信请求参数】：{}\n【微信响应数据】：{}\n【微信接口耗时】:{}",
                    url, "", result,(System.currentTimeMillis() - begin)+"ms");

        }
    }

    /**
     * post请求
     * @param url 请求地址
     * @param params 请求参数
     * @return json格式数据
     * @version 1.0  by wuhao at 2019-03-04
     */
    public static JSONObject post(String url, String params){
        long begin = System.currentTimeMillis();
        String result = "";
        if(!url.startsWith("http")) {
            url = WechatConstants.WX_API_URL + url;
        }
        try {
            result = HttpUtils.post(url, JSONObject.parseObject(params), 5000);;
            return JSONObject.parseObject(result);
        }catch (Exception e){
            logger.error(url,e);
            throw  e;
        }finally {
            logger.info("\n【微信请求地址】: {}\n【微信请求参数】：{}\n【微信响应数据】：{}\n【微信接口耗时】:{}",
                    url, params, result,(System.currentTimeMillis() - begin)+"ms");

        }
    }


    /**
     * post请求,有不是返回json字符串接口
     * @param url 请求地址
     * @param params 请求参数
     * @return json格式数据
     * @version 1.0  by wuhao at 2019-03-04
     */
    public static String post1(String url, String params){
        long begin = System.currentTimeMillis();
        String result = "";
        if(!url.startsWith("http")) {
            url = WechatConstants.WX_API_URL + url;
        }
        try {
            result = HttpUtils.post(url, JSONObject.parseObject(params).toJSONString());;
            return result;
        }catch (Exception e){
            logger.error(url,e);
            throw  e;
        }finally {
            logger.info("\n【微信请求地址】: {}\n【微信请求参数】：{}\n【微信响应数据】：{}\n【微信接口耗时】:{}",
                    url, params, result,(System.currentTimeMillis() - begin)+"ms");

        }
    }

}
